<script setup lang="ts">
import {computed, nextTick, onMounted, ref, watch} from 'vue';
import type { VNode } from 'vue';
import { useAuthStore } from '@/store/modules/auth';
import { useRouterPush } from '@/hooks/common/router';
import { useSvgIcon } from '@/hooks/common/icon';
import { $t } from '@/locales';
import { localStg } from '@/utils/storage';
import {AUTH_TOKEN, USER_INFO} from '@/utils/const';
import {clearAuthStorage} from "@/store/modules/auth/shared";
import {useRouteStore} from "@/store/modules/route";
import {useTabStore} from "@/store/modules/tab";
import {checkVersionUserReviewAction, logoutAction} from "@/service/api";
import UpdateTipsModal from "@/layouts/modules/global-header/components/update-tips-modal.vue";
import {useBoolean} from "~/packages/hooks";
import UpdateLogModal from "@/layouts/modules/global-header/components/update-log-modal.vue";

defineOptions({
  name: 'UserAvatar'
});

const { bool: showTipsModal, setTrue: openTipsModal } = useBoolean();
const { bool: showLogModal, setTrue: openLogModal } = useBoolean();

const authStore = useAuthStore();
const { routerPushByKey, toLogin } = useRouterPush();
const { SvgIconVNode } = useSvgIcon();
const userInfo = localStg.get(USER_INFO);

function loginOrRegister() {
  toLogin();
}

type DropdownKey = 'user-center' | 'update-log' | 'logout';

type DropdownOption =
  | {
      key: DropdownKey;
      label: string;
      icon?: () => VNode;
    }
  | {
      type: 'divider';
      key: string;
    };

const options = computed(() => {
  const opts: DropdownOption[] = [
    {
      label: $t('common.userCenter'),
      key: 'user-center',
      icon: SvgIconVNode({ icon: 'ph:user-circle', fontSize: 18 })
    },
    {
      type: 'divider',
      key: 'divider'
    },
    {
      label: $t('common.updateLog'),
      key: 'update-log',
      icon: SvgIconVNode({ icon: 'streamline:interface-download-desktop-action-actions-computer-desktop-device-display-download-monitor-screen', fontSize: 16 })
    },
    {
      type: 'divider',
      key: 'divider'
    },
    {
      label: $t('common.logout'),
      key: 'logout',
      icon: SvgIconVNode({ icon: 'ph:sign-out', fontSize: 18 })
    }
  ];

  return opts;
});

// const isLogin = computed(() => authStore.isLogin);

const isLogin = ref<boolean>(false);

getLoginStatus();

async function getLoginStatus() {
  const token: string = (localStg.get(AUTH_TOKEN) as string) || '';
  // console.log("Token鉴权")
  isLogin.value = token!.length > 0;
  if (!isLogin.value) {
    setTimeout(() => {
      getLoginStatus();
    }, 500);
  } else {
    const authStore = useAuthStore();
    await authStore.initUserInfo();
    await fetchCheckUpdateLog();
  }
}

// 检查用户是否查看过更新日志
async function fetchCheckUpdateLog() {
  const params: any = {
    moduleId: localStg.get('moduleId') || 1
  };
  const { data, error } = await checkVersionUserReviewAction(params);
  if (!error) {
    // console.log('data: ', data);
    if (data === 0) {
      openTipsModal();
    }
  }
}

const routeStore = useRouteStore();
const tabStore = useTabStore();
// const authStore = useAuthStore();

function logout() {
  window.$dialog?.info({
    title: $t('common.tip'),
    content: $t('common.logoutConfirm'),
    positiveText: $t('common.confirm'),
    negativeText: $t('common.cancel'),
    onPositiveClick: () => {
      logoutAction().then((res) => {
        const { VITE_OTHER_SERVICE_BASE_URL } = import.meta.env;
        const otherUrl = JSON.parse(VITE_OTHER_SERVICE_BASE_URL);

        // window.location.href = 'http://192.168.7.22:28090/aiWeb/login';
        // window.location.href = 'http://xiaoxiangzhiku.tvjoy.cn:28089/aiWeb/login';
        window.location.href = otherUrl.platformLogin;
        // clearAuthStorage();

        authStore.$reset();

        tabStore.cacheTabs();
        routeStore.resetStore();
        // authStore.resetStore();
      });
    }
  });
}

function handleDropdown(key: DropdownKey) {
  if (key === 'logout') {
    logout();
  } else if (key === 'update-log') {
    openLogModal();
  } else {
    // routerPushByKey(key);
    const { VITE_OTHER_SERVICE_BASE_URL } = import.meta.env;
    const otherUrl = JSON.parse(VITE_OTHER_SERVICE_BASE_URL);

    window.location.href = otherUrl.platformSetting;

    // window.location.href = 'http://192.168.7.22:28090/aiWeb/personCenter/userSetting';
    // window.location.href = 'http://xiaoxiangzhiku.tvjoy.cn:28089/aiWeb/personCenter/userSetting';
  }
}
</script>

<template>
  <div>
    <NButton v-if="!isLogin" quaternary @click="loginOrRegister">
      {{ $t('page.login.common.loginOrRegister') }}
    </NButton>
    <NDropdown v-else placement="bottom" trigger="click" :to="false" :options="options" @select="handleDropdown">
      <div>
        <NButton class="header-btn" text round :focusable="false">
          <img class="ml-10px" src="@/assets/imgs/icon-header.png" alt="" width="28" height="28" />
          <span class="ml-10px mr-20px text-12px font-medium">{{ userInfo.user.nickName }}</span>
          <img class="mr-20px" src="@/assets/imgs/header-down.png" alt="" width="8" />
        </NButton>
      </div>
    </NDropdown>
    <UpdateTipsModal v-model:show="showTipsModal" @update-log-click="openLogModal" />
    <UpdateLogModal v-model:show="showLogModal" />
  </div>
</template>

<style scoped lang="scss">
.header-btn {
  display: flex;
  align-items: center;
  justify-content: space-around;
  height: 34px;
  background: rgba(255,255,255,0.6);
  color: #666666;
  border-radius: 17px;
}
.header-btn:hover {
  background: rgba(255,255,255,0.6);
  color: #666666;
}
</style>
